/**
 * require layui(layer、form、upload), kingeditor
 * @param {Object} options
 */


MZForm = function(options){
	return this.init(options);
}


MZForm.fn = MZForm.prototype = {
	frm: null,
	type: 'data_form',				// data_form or config_form
	layui_form: null,
	layui_upload: null,
	types: [{text:'文本', value:'text'}, {text:'隐藏', value:'hidden'}, {text:'数字', value:'number'}, 
		{text:'下拉', value:'select'}, {text:'多选', value:'checkbox'}, {text:'开关', value:'switch'}, 
		{text:'单选', value:'radio'}, {text:'文件', value:'file'}, {text:'文本域', value:'textarea'}, 
		{text:'富文本', value:'richtext'}, {text:'自定义', value:'html'}],
	elements: [],
	data: {},
	_events:{
		submit:[]
	}
}


MZForm.fn.init = function(options){
	var that = this;
	that.frm = options.frm;
	that.elements = options.elements;
	
	var form_html = '', inline_html = '';
	for(var i=0; i<that.elements.length; i++){
		var ele = that.elements[i];
		if('function' == typeof that['_create_' + ele.type] && ele.name){
			if(ele.inline){
				inline_html = '';
				for(; i<that.elements.length; i++){
					ele = that.elements[i];
					if(ele.inline){
						inline_html += '<div class="layui-inline">' + that['_create_' + ele.type](ele) + '</div>';
					}else{
						i--;
						break;
					}
				}
				form_html += '<div class="layui-form-item">' + inline_html + '</div>';
				
			}else{
				var html = that['_create_' + ele.type](ele);
				form_html += '<div class="layui-form-item">' + html + '</div>';
			}
			
			
		}else{
			console.warn('参数错误，已忽略元素');
		}
	}
	
	
	that.frm.innerHTML = form_html;
	layui.use(['form', 'upload'], function(){
	  	that.layui_form = layui.form;
		that.layui_upload = layui.upload;
		that.layui_form.render();
		that._bind_events();
	});
	return that;
}


MZForm.fn.refresh = function(){
	var that = this;
	that.frm = options.frm;
	
	
	that.layui_form.render();
}


MZForm.fn._bind_events = function(){
	var that = this;

	
	//上传
	var uploads = document.getElementsByClassName('btn_upload');
	if(uploads.length){

		that.layui_upload.render({
		    elem: '.btn_upload', 		//绑定元素
		    auto: false, 				//是否自动上传
		    choose: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
		    	layer.load(); //上传loading
		    	
		    	var files = obj.pushFile();
		    	//预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
			    obj.preview(function(index, file, result){
			      console.log(index); //得到文件索引
			      console.log(file); //得到文件对象
			      console.log(result); //得到文件base64编码，比如图片
			      
			      //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增
			      
			      //这里还可以做一些 append 文件列表 DOM 的操作
			      
			      //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
			      //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
			    });
			},
		    done: function(res){
		      	//上传完毕回调
		      	
		      	var hiddenVals = uploads[i].parentElement.getElementsByClassName('ipt_upload_value');
		      	if(hiddenVals.length){
		      		hiddenVals[0].value = res.msg;
		      	}
		      	
		      	layer.closeAll('loading'); //关闭loading
		      	layer.msg("上传成功");
		    },
		    error: function(){
		      	//请求异常回调
		      	layer.closeAll('loading'); //关闭loading
		    }
	  	});
	
	}
  	

	//提交
	this.layui_form.on('submit(*)', function(data){
	  	console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
	  	
	  	var richEditor = that.getById('#editor_id');
		if(richEditor){
			data.field[richEditor.name] = KE.html('editor_id');
		}
		
		var form_data = data.field;
		//多选转为拼接值(或数组)
		for(var key in form_data){
			if(/^.*\[.*\]$/.test(key)){
				var k = key.substr(0, key.indexOf('['));
				var tmp = key.substring(key.indexOf('[')+1, key.indexOf(']'));
				form_data[k] = form_data[k] ? form_data[k] + ',' + tmp : tmp;
				delete form_data[key];
			}
		}
	  	
	  	that._call_event('submit', form_data);
	 	return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});  
}

MZForm.fn.bind = function(type, fun){
	var that = this;
	if(that._events[type]){
		that._events[type].push(fun);
	}
	return that;
}


MZForm.fn._call_event = function(type, params){
	var that = this;
	var evt = that._events[type];
	if(evt){
		for(var i in evt){
			evt[i](params);
		}
	}
	return that;
}



MZForm.fn.getById = function(id){
	return document.getElementById(id);
}


/**
 * 自定义创建元素
 */
MZForm.fn.addElement = function(){
	var that = this;
	
	var content = '<div class="mz-form-element">'; 
	content += '<div class="mz-form-field"><form name="mz_form_field" class="layui-form">';
	content += this._create_text({name:'name', title:'字段名'});
	content += this._create_text({name:'title', title:'字段标题'});
	content += this._create_select({name:'type', title:'类型', value:'text', options:this.types});
	content += '</form></div>';
	

	content += '<div class="mz-form-option" style="display:none;"><form name="mz_form_option" class="layui-form"></form>';
	content += '<button class="layui-btn layui-btn-xs mz-form-option-add">添加选项</button></div>';
	
	
	content += '</div>';
	
	layer.open({
		type: 1,
		area: ['500px', '600px'],
		content: content,
		btn: ['确认', '取消'],
		yes: function(index, layero){
	    	//按钮【按钮一】的回调
	    	layer.close(index);
	    	
	    	var ele = {};
	    	var frmField = document.mz_form_field;
	    	var frmOption = document.mz_form_option;
	    	
	    	ele.name = frmField.name.value;
	    	ele.title = frmField.title.value;
	    	ele.type = frmField.type.value;
	    	
	    	if(frmOption.text){
	    		ele.options = [];
	    		if(frmOption.text.length){
	    			frmOption.text.forEach(function(txt, index){
	    				ele.options.push({text:txt.value, value:frmOption.value[index].value});
	    			})
	    		}else{
	    			ele.options.push({text:frmOption.text.value, value:frmOption.value.value});
	    		}
	    	}
	    	
	    	that.createElement(ele);
	    	that.layui_form.render();
	    	if('file' == ele.type)	that._bind_events();
	  	}
		
	});
	this.layui_form.render();
	
	var divFormEle = document.getElementsByClassName('mz-form-element');
	var divOption = divFormEle[0].getElementsByClassName('mz-form-option');
	divOption[0].style.margin = '20px';
	divOption[0].style.padding = '10px';
	divOption[0].style.border = '1px dashed gray';
	divOption[0].style.borderRadius = '10px';
	divOption[0].style.textAlign = 'center';
	
	this.layui_form.on('select(type)', function(data){
		var type = data.value;
		if(type == 'select' || type == 'radio' || type == 'checkbox'){
			divOption[0].style.display = 'block';
		}else{
			divOption[0].style.display = 'none';
		}
		
	})
	
	divFormEle[0].getElementsByClassName('mz-form-option-add')[0].addEventListener('click', function(e){
		var frmOption = document.mz_form_option;
		var num = 1;
		if(frmOption.text){
			num = frmOption.text.length ?  frmOption.text.length+1 : 2;
		}
		var tmp = '' +
	    '	<label class="layui-form-label">选项'+num+'</label>' +
	    '	<div class="layui-input-block">' +
	    '  		<input type="text" name="text"  lay-filter="text" placeholder="文本"  class="layui-input" style="display:inline-block;width:48%;">' +
	    '  		<input type="text" name="value"  lay-filter="value" placeholder="值"  class="layui-input" style="display:inline-block;width:48%;">' +
	    '	</div>' +
	  	'</div>';
		document.mz_form_option.innerHTML += tmp;
	})
	
}


/**
 * 用于外部创建
 * @param {Object} ele
 */
MZForm.fn.createElement = function(ele){
	var that  = this;
	if('function' == typeof that['_create_' + ele.type] && ele.name){
		that.frm.innerHTML += that['_create_' + ele.type](ele);
	}
}


MZForm.fn._create_html = function(ele){
    if('function' == typeof ele.render){
        return ele.render();
    }
	return ele.content;
}


MZForm.fn._create_text = function(ele){
	ele.value = ele.value || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="text" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
	    '	</div>' +
	  	'';
	return tmp;
}

MZForm.fn._create_number = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="number" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
	    '	</div>' +
	  	'';
	return tmp;
}

/**
 * 下拉单选
 * @param {Object} ele
 */
MZForm.fn._create_select = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<select name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" >';
	for(var i in ele.options){
		var opt = ele.options[i];
		tmp += '	<option value="'+opt.value+'">'+opt.text+'</option>';
	}
	tmp += '	</select>' +
	    '	</div>' +
	  	'';
	return tmp;
}

/**
 * 复选框
 * @param {Object} ele
 */
MZForm.fn._create_checkbox = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">';
	var values = ele.values || [];    
	for(var i in ele.options){
		var opt = ele.options[i];
		var checked = values.indexOf(opt.value) >= 0 ? 'checked' : '';
		tmp += '	<input type="checkbox" name="'+ele.name+'['+opt.value+']" title="'+opt.text+'" '+checked+'>';
	}
	tmp += '</div>' +
	  	'';
	return tmp;
}


/**
 * 开关
 * @param {Object} ele
 */
MZForm.fn._create_switch = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var checked = ele.value?'checked':'';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="checkbox" name="'+ele.name+'" '+checked+' lay-filter="'+ele.name+'" lay-skin="switch">' +
	    '	</div>' +
	  	'';
	return tmp;
}


/**
 * 单选
 * @param {Object} ele
 */
MZForm.fn._create_radio = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">';
	for(var i in ele.options){
		var opt = ele.options[i];
		var checked = ele.value == opt.value ? 'checked' : '';
		tmp += '	<input type="radio" name="'+ele.name+'" value="'+opt.value+'" title="'+opt.text+'" '+checked+' >';
	}
	tmp += '</div>' +
	  	'';
	return tmp;
}



MZForm.fn._create_textarea = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<textarea name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" placeholder="请输入"  class="layui-textarea"></textarea>' +
	    '	</div>' +
	  	'';
	return tmp;
}


MZForm.fn._create_richtext = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<textarea id="editor_id" name="'+ele.name+'"  ></textarea>' +
	    '	</div>' +
	  	'';
	KE.show({id:'editor_id'});
	if(ele.value)	KE.html('editor_id', ele.value);
	return tmp;
}


MZForm.fn._create_file = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	ele.value = ele.value || '';
	ele.accept = ele.accept || 'images';
	ele.url = ele.url || '/upload';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '		<div id="upload_preview"></div>' + 
	    '  		<input type="hidden" class="ipt_upload_value" name="'+ele.name+'" value="'+ele.value+'" />' +
	    '		<button type="button" class="layui-btn btn_upload" lay-data="{url: \'/'+ele.url+'/\', accept: \''+ele.accept+'\' }" > ' +
		'  			<i class="layui-icon">&#xe67c;</i>上传' +
		'		</button>' + 
	    '	</div>' +
	  	'';

	return tmp;
}




MZForm.fn._create_buttons = function(ele){
	var tmp = '' +
	    '	<div class="layui-input-block">' +
	    '  		<button class="layui-btn" lay-submit lay-filter="*">立即提交</button>' +
	    '  		<button class="layui-btn" type="reset">重置</button>' +
	    '	</div>' +
	  	'';
		
	return tmp;
}





/*

<input type="text" lay-verify="email"> 
 
还同时支持多条规则的验证，如下：
<input type="text" lay-verify="required|phone|number">

form.verify({
  username: function(value, item){ //value：表单的值、item：表单的DOM对象
    if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
      return '用户名不能有特殊字符';
    }
    if(/(^\_)|(\__)|(\_+$)/.test(value)){
      return '用户名首尾不能出现下划线\'_\'';
    }
    if(/^\d+\d+\d$/.test(value)){
      return '用户名不能全为数字';
    }
  }
  
  //我们既支持上述函数式的方式，也支持下述数组的形式
  //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
  ,pass: [
    /^[\S]{6,12}$/
    ,'密码必须6到12位，且不能出现空格'
  ] 
}); 



* 
* */